package org.micode.common.helper;

import org.micode.common.enums.ResultEnum;
import org.micode.common.exception.DataException;
import org.micode.common.domain.ApiResult;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;

@Slf4j
public class MethodHelper {

    public static <T, R> R invoke(Function<T, R> method, T t) {
        return method.apply(t);
    }

    public static <T, R> R invokeAndFailReturnNull(Function<T, R> method, T t) {
        try {
            return method.apply(t);
        } catch (Exception e) {
            log.error("Invoke failed", e);
            return null;
        }
    }

    public static <T, R> R invokeRemote(Function<T, ApiResult<R>> method, T t) {
        ApiResult<R> ret = method.apply(t);
        if (ResultEnum.SUCCESS.getCode() != ret.getCode()) {
            log.error("Method call exception: {}({})", ret.getMsg(), ret.getCode());
            throw new DataException(ret.getMsg() + "(" + ret.getCode() + ")");
        }
        return ret.getData();
    }

}
